<?php

$db_obj = new db_obj();
$task_obj = new task_obj();
$task_phorum_obj = new task_phorum_obj();
$client_obj = new client_obj();
$user_obj = new user_obj();
$filter_obj = new filter_obj();
$record_obj = new record_obj();
$tariff_obj = new tariff_obj();
$lock_obj = new lock_obj();

if (isset($_REQUEST['action']) && !empty($_REQUEST['action'])) {
    switch ($_REQUEST['action']) {
        case 'add_record':

            $date = explode('/', $_REQUEST['record']['date']);
            $filter = array(
                'month' => $date[1],
                'year' => $date[2],
                'type' => 'record'
            );

            $is_locked = $lock_obj->getLocks($filter);
            if (error_obj::isError($is_locked)) {
                error_obj::setError($is_locked, UNEXCEPTED);
            } elseif (!empty($is_locked)) {
                error_obj::setError($is_locked, PERIOD_IS_LOCKED);
            } else {
                $in_data = $_REQUEST['record'];
                $in_data['unit_price'] = $in_data['price'];
                unset($in_data['price']);
                $in_data['date'] = base_obj::convertDateTo($in_data['date']);
                $newRecordId = $record_obj->addRecord($in_data);
                if (error_obj::isError($newRecordId)) {
                    error_obj::setError($newRecordId, UNEXCEPTED);
                } else {
                    $change_obj = new change_obj();
                    $in_data = array(
                        'rel_id' => $newRecordId,
                        'type' => CHANGES_TYPE_TSDR,
                        'status' => CHANGES_STATUS_NEW,
                        'date' => time()
                    );
                    $change_obj->add_change($in_data);
                    base_obj::redirect(ROOT . '?input=timesheets');
                }
            }
            break;
        case 'edit_record':
            $recordId = (int) $_REQUEST['recordId'];
            $record_taskId = (int) $_REQUEST['record_taskId'];
            if (empty($recordId))
                break;
            $originalRecord = $record_obj->getRecordById($recordId);
            $in_data = $_REQUEST['record'];
            $in_data['unit_price'] = $in_data['price'];
            unset($in_data['price']);
            $in_data['date'] = base_obj::convertDateTo($in_data['date']);
            if (!isset($in_data['after_hours']))
                $in_data['after_hours'] = 0;
            $in_data['last_update'] = date("Y-m-d H:i:s");
            $in_data['last_editor'] = $_SESSION['user']['user_id'];
            $result = $record_obj->editRecord($in_data, $recordId);
            if (error_obj::isError($result)) {
                error_obj::setError($result, UNEXCEPTED);
            } else {
                $change_obj = new change_obj();
                $change_obj->add_change_with_records_compare($recordId, $originalRecord);
                $task_obj->updateTaskRate($record_taskId);
                base_obj::redirect(ROOT . '?input=timesheets');
            }
            break;
    }
}

$GLOBALS['template_data']['months'] = array();
for ($i = 1; $i < 13; $i++) {
    $GLOBALS['template_data']['months'][$i] = date("F", mktime(12, 0, 0, $i, 1, 2013));
}

$GLOBALS['template_data']['years'] = array();
for ($i = 2013; $i < date("Y") + 2; $i++) {
    $GLOBALS['template_data']['years'][$i] = $i;
}

if (!isset($_SESSION['timesheets_pager'])) {
    $_SESSION['timesheets_pager'] = $GLOBALS['timesheets_pager'];
}

if (!isset($_SESSION['timesheets_order'])) {
    $_SESSION['timesheets_order'] = $GLOBALS['timesheets_order'];
}

if (isset($_SESSION['timesheets_fulltext']) && !empty($_SESSION['timesheets_fulltext']))
    $GLOBALS['template_data']['currentFulltext'] = $_SESSION['timesheets_fulltext'];

$filter = array();

$currentFilter = array();

if (isset($_SESSION['timesheets_filter'])) {
    $filter = $_SESSION['timesheets_filter'];
    $result = $filter_obj->updateFilter($_SESSION['user']['user_id'], 'timesheets_filter', $filter);
    if (error_obj::isError($result)) {
        error_obj::setError($result, UNEXCEPTED);
    }
    foreach ($_SESSION['timesheets_filter'] as $f => $v) {
        switch ($f) {
            case "type":
                $currentFilter[$f] = $record_obj->getTypeOfRecordById($v);
                $currentFilter[$f] = $currentFilter[$f]['type_of_record'];
                break;
            case "client":
                $currentFilter[$f] = $client_obj->getClient($v);
                $currentFilter[$f] = $currentFilter[$f]['name'];
                break;
            case "user_id":
                $currentFilter[$f] = $user_obj->getUserById($v);
                $currentFilter[$f] = $currentFilter[$f]['name'] . " " . $currentFilter[$f]['surname'];
                break;
            case "tariff":
                $currentFilter[$f] = $tariff_obj->getTariffById($v);
                if (!empty($currentFilter[$f]))
                    $currentFilter[$f] = $currentFilter[$f]['title'];
                else
                    $currentFilter[$f] = '-';
                break;
            case "amount":
                $currentFilter[$f] = $v;
                break;
            case "unit_price":
                $currentFilter[$f] = $v;
                break;
            case "date":
                $currentFilter[$f] = base_obj::convertDateTo($v, 'dd/mm/yyyy H:i:s', 'datetime');
                break;
            case "month":
                $currentFilter[$f] = $GLOBALS['template_data']['months'][$v];
                break;
            case "monthm":
                $currentFilter[$f] = $GLOBALS['template_data']['months'][$v];
                break;
            case "year":
                $currentFilter[$f] = $v;
                break;
            case "after_hours":
                if ($v == 1)
                    $currentFilter[$f] = 'Yes';
                else
                    $currentFilter[$f] = 'No';
                break;
            case "attention":
                if ($v == 1)
                    $currentFilter[$f] = 'Yes';
                else
                    $currentFilter[$f] = 'No';
                break;
        }
    }
}

$GLOBALS['template_data']['currentFilter'] = $currentFilter;

if (!isset($_GET['page'])) {
    $_GET['page'] = 0;
}

$limit = ($_GET['page'] * $_SESSION['timesheets_pager']) . ' ,' . $_SESSION['timesheets_pager'];

if ($_SESSION['user']['profile']['userlevel'] == USER_TYPE_CLIENT) {
    $filter['clients'] = $_SESSION['user']['clients'];
}

if (isset($_REQUEST['af']) && !empty($_REQUEST['af'])) {
    $filter = array();
    $filter = json_decode(base64_decode(urldecode($_REQUEST['af'])), true);
    $GLOBALS['template_data']['currentFilter'] = array();
}

if (isset($_SESSION['timesheets_fulltext']) && !empty($_SESSION['timesheets_fulltext'])){
    $PAGER_COUNT = $record_obj->getListOfRecordsByFulltext($_SESSION['timesheets_fulltext'], $filter, $_SESSION['timesheets_order'], '', 'COUNT(*)');
    $records = $record_obj->getListOfRecordsByFulltext($_SESSION['timesheets_fulltext'], $filter, $_SESSION['timesheets_order'], $limit);
} else {
    $PAGER_COUNT = $record_obj->getListOfRecords($filter, $_SESSION['timesheets_order'], '', 'COUNT(*)');
    $records = $record_obj->getListOfRecords($filter, $_SESSION['timesheets_order'], $limit);
}
$PAGER_COUNT = $PAGER_COUNT[0][0];
$GLOBALS['template_data']['total_count'] = $PAGER_COUNT;

$GLOBALS['template_data']['currentOrder'] = array(
    $_SESSION['timesheets_order']['col'],
    $_SESSION['timesheets_order']['order']
);

foreach ($records as $key => $record) {
    $records[$key]['date_formated'] = base_obj::convertDateTo($record['date'], 'dd/mm/yyyy H:i:s', 'datetime');
    $records[$key]['locked'] = 0;
    if ($lock_obj->isRecordLocked($records[$key]['date_formated'])) {
        $records[$key]['locked'] = 1;
    }
    $records[$key]['client_info'] = $client_obj->getClient($record['client']);
    $records[$key]['user_info'] = $user_obj->getUserById($record['user_id']);
    $records[$key]['type_info'] = $record_obj->getTypeOfRecordById($record['type']);
    if ($record['tariff'] != -1)
        $records[$key]['tariff_info'] = $tariff_obj->getTariffById($record['tariff']);
    else
        $records[$key]['tariff_info']['title'] = '-';
}


$GLOBALS['template_data']['records'] = $records;

$pager = $db_obj->pager($PAGER_COUNT, $_GET['page'], $_SESSION['timesheets_pager'], $filter);

$GLOBALS['template_data']['pager'] = $pager;

$filter = array();
$filter['active'] = 0;
if ($_SESSION['user']['profile']['userlevel'] == USER_TYPE_CLIENT) {
    $filter['clients'] = $_SESSION['user']['clients'];
}
$GLOBALS['template_data']['clients'] = $client_obj->getAllClients('contactPerson, klient_id, name, bad_payer', $filter, 'name ASC');


/////////////// start of record data
$GLOBALS['template_data']['rtypes'] = $record_obj->getRecordTypes();
$filter = array();
$filter['type_of_record'] = $GLOBALS['template_data']['task_data']['type'];
$GLOBALS['template_data']['rtariffs'] = $tariff_obj->getTariffs("Id, title", $filter, array('col' => 'title', 'orderBy' => 'title', 'order' => 'ASC', 'table' => '', 'connector' => ''));
$filter = array(
    'client' => 11,
    'active' => 1
);
$GLOBALS['template_data']['rusers'] = $user_obj->getUsers('users_id, name, surname', $filter);
$GLOBALS['template_data']['isCopy'] = 0;
if (isset($_REQUEST['copy_id']) && !empty($_REQUEST['copy_id']) && is_numeric($_REQUEST['copy_id'])) {
    $toCopy = $record_obj->getRecordById($_REQUEST['copy_id']);
    if (!error_obj::isError($toCopy) && !empty($toCopy)) {
        $filter = array();
        $filter['type_of_record'] = $toCopy['type'];
        $GLOBALS['template_data']['rtariffs'] = $tariff_obj->getTariffs("Id, title", $filter, array('col' => 'title', 'orderBy' => 'title', 'order' => 'ASC', 'table' => '', 'connector' => ''));
        $GLOBALS['template_data']['prefill'] = $toCopy;
        $GLOBALS['template_data']['prefill']['date'] = base_obj::convertDateTo($GLOBALS['template_data']['prefill']['date'], "dd/mm/yyyy", 'date');
        $GLOBALS['template_data']['isCopy'] = 1;
    }
}

if ($GLOBALS['template_data']['isCopy'] != 1) {
    $GLOBALS['template_data']['prefill']['date'] = date("d/m/Y");
    $GLOBALS['template_data']['prefill']['client'] = $_SESSION['user']['clientFilter'];
    $GLOBALS['template_data']['prefill']['user_id'] = $_SESSION['user']['user_id'];
    $GLOBALS['template_data']['prefill']['type'] = 1;
    $filter = array();
    $filter['type_of_record'] = $GLOBALS['template_data']['prefill']['type'];
    $GLOBALS['template_data']['rtariffs'] = $tariff_obj->getTariffs("Id, title", $filter, array('col' => 'title', 'orderBy' => 'title', 'order' => 'ASC', 'table' => '', 'connector' => ''));
}

if (isset($_REQUEST['editRecord']) && !empty($_REQUEST['editRecord']) && is_numeric($_REQUEST['editRecord'])) {
    $toEdit = $record_obj->getRecordById($_REQUEST['editRecord']);
    if ($lock_obj->isRecordLocked(base_obj::convertDateTo($toEdit['date'], "dd/mm/yyyy", 'date'))) {
        error_obj::setError(new error_obj("locked record", __FILE__, ''), PERIOD_IS_LOCKED);
        $_REQUEST['editRecord'] = -1;
    } else {
        if (!error_obj::isError($toEdit) && !empty($toEdit)) {
            $filter = array();
            $filter['type_of_record'] = $toEdit['type'];
            $GLOBALS['template_data']['rtariffs_edit'] = $tariff_obj->getTariffs("Id, title", $filter, array('col' => 'title', 'orderBy' => 'title', 'order' => 'ASC', 'table' => '', 'connector' => ''));
        }
    }
}
?>
